package com.zzzzzz.acct;

import java.util.Date;
import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import com.zzzzzz.acct.User;
import com.zzzzzz.common.page.Page;
import com.zzzzzz.core.exception.SystemException;
import com.zzzzzz.core.exception.UserActiveException;
import com.zzzzzz.core.exception.ZzzzzzException;

@Service("userService")
public class UserServiceImpl implements UserService{
	
	@Resource
	private UserDao userDao;
	
	public void add(SignUpForm signUpForm) {
		User user = signUpForm.toUser();
		userDao.add(user);
	}

	public void edit(UserEditForm userEditForm) {
		userDao.edit(userEditForm);
	}
	
	public void editStatus(Long id, String status, Date updTime) {
		userDao.editStatus(id, status, updTime);
	}
	
	public void editPic(Long id, String picId) {
		userDao.editPic(id, picId);
	}
	
	public void editEmail(UserEmailEditForm userEmailEditForm) {
		userDao.editEmail(userEmailEditForm);
	}
	
	public void editPassword(UserPasswordEditForm userPasswordEditForm) {
		userDao.editPassword(userPasswordEditForm);
	}
	
	public User findById(Long id) {
		return userDao.findById(id);
	}

	public User findByEmail(String email) {
		return userDao.findByEmail(email);
	}
	
	public Page<UserView> findAll(Page<UserView> page) {
		return userDao.findAll(page);
	}
	
	public void login(String email, String password, boolean rememberMe) throws ZzzzzzException, SystemException {
		User user = findByEmail(email);
		if(user != null) {
			//is activated
	    	if(user.getStatus() == 1){
				throw new UserActiveException();
	    	}else{
	            Subject currentUser = SecurityUtils.getSubject();
	    		if (!currentUser.isAuthenticated()) {
		            UsernamePasswordToken token = new UsernamePasswordToken(email, password, rememberMe);
		        	currentUser.login(token);
	    		}
	    	}
		}
	}
	
	public Boolean isSignedIn() {
		Subject currentUser = SecurityUtils.getSubject();
		return currentUser.isAuthenticated();
	}
	
	public User findCurrentUser() throws ZzzzzzException {
		Subject currentUser = SecurityUtils.getSubject();
		User user = null;
		String currentUserId = (String) currentUser.getPrincipal();
		if( currentUserId != null ) {
			user = findById(new Long(currentUserId));
		}
		return user;
	}
	
	public String findCurrentUserId() {
		return (String) SecurityUtils.getSubject().getPrincipal();
	}
}
